# -*- coding: utf-8 -*-
from onlineutils import crypto

__author__ = 'vladbranzei'

import cherrypy, json, time


def jsonify(f):
    def _jsonify(*args, **kwargs):
        return json.dumps(f(args[0], **kwargs))
    return _jsonify

def validate(fn):
    def wrapped(*args, **kwargs):
        try:
            token = kwargs['token']
            tokens = token.split('|')
            expiration_time = float(tokens[4])
            current_time = time.time()
            three_hours = 3 * 60 * 60

            if current_time - three_hours > expiration_time:
                cherrypy.response.status = 401
            else:
                tok = tokens[0] + "|" + tokens[1] + "|" + tokens[2] + "|" + tokens[3] + "|" + tokens[4] + "|"
                hash = crypto.encrypt(tok)
                if tokens[5] == hash:
                    result = fn(args[0], kwargs)
                    return result
                else:
                    cherrypy.response.status = 401
                    return None
                    #log user credentials, tried to handmade a token
        except KeyError as e:
            cherrypy.response.status = 400
            return None
    return wrapped

def has_scope(wanted_scope):
    def _has_scope(f):
        def __has_scope(*args):
            try:
                token = args[1]['token']
                tokens = token.split('|')
                scopes = tokens[2]
                scopes_list = scopes.split()
                for scope in scopes_list:
                    if scope == wanted_scope:
                        result = f(args[0],args[1])
                        return result
                    else:
                        continue
                cherrypy.response.status = 401
                return None
            except KeyError as e:
                cherrypy.response.status = 400

        return __has_scope
    return _has_scope


def validate_game(i_game):
    games = ['1512']
    try:
        games.index(i_game)
        return True
    except ValueError as e:
        return False

def validate_scopes(i_scopes):
    my_list = i_scopes.split()
    aux_list = list(my_list)
    scopes = ['auth', 'auth_admin', 'leaderboard']
    my_scopes = ''
    for scope in my_list:
        try:
            scopes.index(scope)
            my_scopes += scope + ' '
        except ValueError as e:
            aux_list.remove(scope)

    if aux_list:
        return my_scopes.strip()
    else:
        return False

